package com.example.administrator.langyouapplication;


import java.net.URLEncoder;

import android.annotation.TargetApi;
import android.app.Activity;

import android.content.ClipData;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity {

//    private final String host = "47.92.134.153:8080";
    private final String host = "www.dayu90du.top";
    private final String urlAddress = "http://" + host;

    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;

//    private ProgressBar progressBar;
    WebView webView;
    final String mimeType = "text/html";

    final String encoding = "utf-8";


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = getIntent();

        String url = String.valueOf(intent.getData());

        webView = (WebView) findViewById(R.id.webView);
		/*在webview加载网页时，不调用第三方浏览器打开的办法：
		 * 设置WebViewClient，并重写WebViewClient的shouldOverrideUrlLoading方法
		 * 返回true为不调用，反之 false为调用第三方浏览器
		 */

        WebSettings settings = webView.getSettings();
//        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setUserAgentString("app/langyouwenhua_app");
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
//        settings.setAppCacheEnabled(true);  //开启缓存功能

        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 设置可以访问文件
//        settings.setAllowFileAccess(true);
        settings.setDefaultTextEncodingName("utf-8");
        //重新设置websettings
//        settings.setBuiltInZoomControls(true);
//        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//        settings.setUseWideViewPort(true);
//        settings.setLoadWithOverviewMode(true);
//        settings.setSaveFormData(true);
//        settings.setGeolocationEnabled(true);

        //处理请求，request
        webView.setWebViewClient(new MyWebViewClient());
        //处理js什么的
        webView.setWebChromeClient(new WebChromeClient() {

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android  >= 3.0
            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }
        });

//        String targetUrl = "file:///android_asset/up.html";
//        webView.loadUrl(targetUrl);
        //出现net::ERR_CACHE_MISS错误提示
        //使用缓存的方式是基于导航类型。正常页面加载的情况下将缓存内容。当导航返回,
        //内容不会恢复（重新加载生成）,而只是从缓存中取回内容
//        if (Build.VERSION.SDK_INT >= 19) {
//            webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//        }
        webHtml(url);

    }

    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }




    private class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideKeyEvent(WebView view,KeyEvent event){
            return super.shouldOverrideKeyEvent(view,event);
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i(url,"qqqq");
//            view.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

            if (url.equals(urlAddress+"/apptoweb")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            }else if (url.equals(urlAddress+"/ly_app/app-debug15.apk")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;

            }else if(view.getUrl().indexOf("http://www.dayu90du.top/contacts.html")!=-1){

                MainActivity.this.finish();
                return true;

            }else if(view.getUrl().equals(url)){
                return false;
            }else if(view.getUrl().indexOf("http://www.dayu90du.top:8082/login")!=-1||
                    view.getUrl().indexOf("http://www.dayu90du.top/shiro-cas")!=-1||
                    view.getUrl().indexOf("http://www.dayu90du.top:8082/logout")!=-1){
                return false;

            }else{
                Intent intent = new Intent(MainActivity.this,MainActivity.class);
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                MainActivity.this.startActivityForResult(intent,0);
                return true;
            }

        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);

//            progressBar.setVisibility(View.GONE);
        }
    }

    //flipscreen not loading again
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    // 捕捉“回退”按键，让WebView能回退到上一页，而不是直接关闭Activity。
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
//            webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
//            webView.goBack();
            /*给上一个Activity返回结果*/
            MainActivity.this.setResult(RESULT_OK,new Intent());/*结束本Activity*/
            MainActivity.this.finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //重写onKeyDown(keyCode, event)方法 改写物理按键 返回的逻辑
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        // TODO Auto-generated method stub
//        if(keyCode==KeyEvent.KEYCODE_BACK)
//        {
//            if(webView.canGoBack())
//            {
//                webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
////                webView.goBack();//返回上一页面
//                finish();
//            }
//            else
//            {
//                System.exit(0);//退出程序
//            }
//        }
////        return false;
//        return super.onKeyDown(keyCode, event);
//    }
    /**
     * 显示网页
     */
    private void webHtml(String urlAddress) {
        try {
            webView.loadUrl(urlAddress);
        } catch (Exception ex) {

            ex.printStackTrace();
        }
    }



}

